package com.tanxi521.springboot.service.impl;

import com.tanxi521.springboot.mapper.PlayerAccountMapper;
import com.tanxi521.springboot.mapper.PlayerMapper;
import com.tanxi521.springboot.pojo.Player;
import com.tanxi521.springboot.pojo.PlayerAccount;
import com.tanxi521.springboot.service.PlayerService;
import com.tanxi521.springboot.utils.SHA256Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class PlayerServiceImpl implements PlayerService {

    @Resource
    private PlayerMapper playerMapper;

    @Resource
    private PlayerAccountMapper playerAccountMapper;

    @Override
    public int regNewPlayer(Player player) {
        if ( 0 <= playerMapper.selectByOnlyCode(player)) return 0;
        int insert = 0;
        PlayerAccount playerAccount = new PlayerAccount();
        String password = player.getPassword();
        String[] split = UUID.randomUUID().toString().split("-");
        String salt = split[1] + split[4];
        String inPass = "$SHA$" + salt + "$" + SHA256Util.getSHA256(password + salt);

        playerAccount.setRealname(player.getPlayerName());
        playerAccount.setUsername(player.getPlayerName().toLowerCase());
        playerAccount.setPassword(inPass);
        playerAccount.setIp("255.255.255.255");
        playerAccount.setRegip("mc.tanxi521.com");
        playerAccount.setRegdate(new Date().getTime());
        playerAccount.setWorld("world");
        playerAccount.setX(0.0);
        playerAccount.setY(0.0);
        playerAccount.setZ(0.0);
        playerAccount.setIslogged((short) 0);
        playerAccount.setHassession((short) 0);
        insert += playerAccountMapper.insert(playerAccount);
        insert += playerMapper.insert(player);
        return insert;
    }
}
